package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.transaction.api.dto.OrderResultDTO;
import com.huiminpay.transaction.api.dto.PayChannelParamDTO;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.api.service.IPlatformChannelService;
import com.huiminpay.transaction.api.service.ITransactionService;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : PayController
 * @Author : 阿泽
 * @Date: 2021/8/12 19:35
 * @Description :
 */
@Controller
@Slf4j
public class PayController {
    @Reference
    ITransactionService transactionService;
    @Reference
    IPlatformChannelService platformChannelService;
    @GetMapping("qr/{token}")
    public String entry(@PathVariable String token, HttpServletRequest request) throws Exception {
        //1.解析token数据 拿到地址栏信息
        String s = EncryptUtil.decodeUTF8StringBase64(token);
        PayOrderDTO payOrderDTO = JSON.parseObject(s, PayOrderDTO.class);
        log.info("{}",payOrderDTO);

        //2.判断当前请求是来自支付宝还是微信（head中的user-agent来判断的 ）
        String userAgent = request.getHeader("User-Agent");
        if (userAgent!=null&&userAgent.contains("AlipayClient")){
            //支付宝支付
            return "forward:/pay-page?"+ ParseURLPairUtil.parseURLPair(payOrderDTO);
        }

        return "forward:/pay-page?"+ ParseURLPairUtil.parseURLPair(payOrderDTO);
    }

    @RequestMapping("pay-page")
    public String payPage(){
        return "pay";
    }

    @ApiOperation("支付宝下单")
    @PostMapping("createAliPayOrder")
    public void createAlipayOrder(OrderConfirmVO orderConfirmVO, HttpServletResponse response) throws Exception {

        PayOrderDTO payOrderDTO = new PayOrderDTO();
        BeanUtils.copyProperties(orderConfirmVO,payOrderDTO);

        //注意参数转换问题 订单金额
        String ta = AmountUtil.changeY2F(orderConfirmVO.getTotalAmount());
        payOrderDTO.setTotalAmount(Integer.valueOf(ta));
        payOrderDTO.setStoreId(Long.valueOf(orderConfirmVO.getStoreId()));
        String alipayHtml =transactionService.createAlipayOrder(payOrderDTO);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(alipayHtml);
        response.getWriter().close();
        response.getWriter().flush();

    }

    @ApiOperation("支付宝异步通知")
    @PostMapping("alipay/notify")
    public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws AlipayApiException, IOException {
        //获取支付宝请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> map = new HashMap<>();
        parameterMap.keySet().forEach(key->{
            map.put(key,parameterMap.get(key)[0]);
        });
        log.info("{}",map);

        //1.验证签名
        String appId = map.get("app_id"),platformChannel = "huimin_c2b",payChannel="ALIPAY_WEB";
        PayChannelParamDTO paramDTO = platformChannelService.queryParamByAppPlatformAndPayChannel(appId, platformChannel, payChannel);
        String param = paramDTO.getParam();
        AliConfigParam aliConfigParam = JSON.parseObject(param, AliConfigParam.class);


        String publickey = aliConfigParam.getAlipayPublicKey(); //支付宝公钥
        boolean b = AlipaySignature.rsaCheckV1(map, publickey, "UTF-8", "RSA2");
        if (!b){
            response.getWriter().write("error");
        }

        //2.更新状态
        //支付宝状态转系统状态
        String trade_status = map.get("trade_status");
        String tradeState = null;
        if (trade_status.equals("TRADE_CLOSED")){
            //
            tradeState = "4";
        }else if (trade_status.equals("TRADE_SUCCESS")){
            tradeState = "2";

        }else if (trade_status.equals("TRADE_FINISHED")){
            tradeState = "3";

        }
        String outTradeNo = map.get("out_trade_no");
        OrderResultDTO orderResultDTO = new OrderResultDTO();
        orderResultDTO.setTradeState(tradeState);
        orderResultDTO.setOutTradeNo(outTradeNo);
        orderResultDTO.setPaySuccessTime(LocalDateTime.now());
        transactionService.updatePayOrderByTredeNo(orderResultDTO);
        response.getWriter().write("error");
        //3.如果成功就回写success
        response.getWriter().flush();
        response.getWriter().close();


    }
    @ApiOperation("订单号查询对接api")
    @GetMapping("alipay/{OutTradeNo}")
    public void selectByOrdelId(@PathVariable String OutTradeNo, HttpServletResponse httpServletResponseresponse) throws AlipayApiException, IOException {
        String serverUrl ="https://openapi.alipaydev.com/gateway.do";
        String Appid ="2021000118602314";
        String privateKey ="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHz4kBcAM2DSLnH++VWdpkueimFFdUO7BfWRcrhcTmgcWsH0DL5z9SN74bv71LYNvknwt857HZEu9KWPB1G7k02waj0fzVYo/GG+98TrnBYNqdeJ0v/7MaKkvSWGaHx7N4Ggr6lY3JxQD5ictrkoSCMkxM1Yr4dVJSnXXw1bMevR2e8ClmWvlJqk5Ytjmf98bEp+iqnBmHammHPt/9dEMbmfw7ltnSQqYRVZq+EA58LIolnBkd/1/ctuA2ZeQLlno4+KoynIy3JLiDmWyWjjv4Guuml9twAVpl0xAeBA4MI+s7K6EcDeeDfUGivrK8m1Tni5nsYI3BfWq/oEMfKoMnAgMBAAECggEAF5UoD3Jf/qYoQ20igtcbDp5elhN6hyeQVoCWWn2sUqRoZzs9E5PUhmir2GyV8+qXqXEYEwLpm7w/X+AFaVz/S/y52OX02F6Mp44ugtZr2CYNR16v9rVQNztcvZ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PHMyehuQ7D5PA5VBWiF";
        String format ="json";
        String charset ="utf-8";
        String aliPayPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnq7V1cGCdEx9CsDMvEW+y4OP67+9+6buTLsgrXEDEDZohPgah5s2u92RZnYLMWy+5/YgEmEkigOi4Z4Qq7j4g9+Mz3Vw/b9Wz0IhmNxSj3R07v9I30FerEs8Xt2KRjYFgTxfb9PhQogo9aoV41SnacsoERkqABkYqOCO/UpkW4eJ58cCPltPjL9+u0HD53pr9Jb//HTWDVRQgN4yuAX9BmXmkfxrmywTyU9w8RtoFXgeJw6TdZpjKioGC7V6S5+WSMGQcXdM3fISchBxqTnreOnWYZhTEK9hl6YukB7yXxqRse6mFoxVn8nZT6oiI1iba7L0JzgWOwBzPMYGQcx4PQIDAQAB";
        String signType = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,Appid,privateKey,format,charset,aliPayPublicKey,signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();


        AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
        alipayTradeWapPayModel.setOutTradeNo(OutTradeNo);
        request.setBizModel(alipayTradeWapPayModel);
        httpServletResponseresponse.setContentType("text/html;charset=utf-8");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            String body = response.getBody();
            httpServletResponseresponse.getWriter().write(body);
        } else {
            httpServletResponseresponse.getWriter().write("error");
        }
        httpServletResponseresponse.getWriter().flush();
        httpServletResponseresponse.getWriter().close();

    }

}
